subroutine sim_dec(nlw,ninc,glw,lglw,C,A,cash,income,tty,indy,F,Fy,simC, simA, simS, simB, simBpart, simP)
    
REAL, INTENT(IN) :: C(nlw,ninc), A(nlw,ninc), glw(nlw,1), lglw(nlw,1)
REAL, INTENT(IN) :: cash, income,tty, F, Fy
INTEGER, INTENT(IN) :: indy
INTEGER :: i_lw, ic1, ic2
REAL :: ttc, cash2, sav
real :: maxA, minA, A11, A12, A21
REAL, INTENT(OUT) :: simC, simA, simS, simB, simBpart, simP


simP=0.0
cash2 = cash+income
CALL ntoil(log(cash),lglw(:,1),nlw,i_lw) !need equally-spaced grid for ntoil
ic1 = i_lw
ic2 = i_lw+1 
ttc = (cash-glw(ic1,1))/(glw(ic2,1)-glw(ic1,1))
ttc = MAX(MIN(1.0,ttc),0.0)
!the cash-on-hand index below, in A and C, refers to cash before any participation costs are paid
simC = (1-tty)*((1-ttc)*C(ic1,indy)+ttc*C(ic2,indy))+ tty*((1-ttc)*C(ic1,indy+1)+ttc*C(ic2,indy+1))  

!due to the per-period cost, for low values of cash we have A=0. If we have in one of those grids points here then we don't want to interpolate.
minA = min(A(ic1,indy),A(ic1,indy+1),A(ic2,indy),A(ic2,indy+1))
!if all values are positive we are fine
if (minA>0) then
   simA = (1-tty)*((1-ttc)*A(ic1,indy)+ttc*A(ic2,indy))+tty*((1-ttc)*A(ic1,indy+1)+ttc*A(ic2,indy+1))  
else
!compute max to fill in zeros if necessary (values should be at least equal to max just after the last zero)
    maxA = max(A(ic1,indy),A(ic1,indy+1),A(ic2,indy),A(ic2,indy+1))
    A11 = A(ic1,indy)
    A12 = A(ic1,indy+1)
    A21 = A(ic2,indy)
!if (A(ic2,indy+1) is zero then all others should be zero also    
    if (A(ic2,indy+1).eq.0.0) then
       simA = 0.0   
    else
       if (A(ic1,indy).eq.0.0) then
          if ((ttc<0.5).and.(tty<0.5)) then 
             simA = 0.0   
          else    
           A11 =  maxA
          end if
        end if   
       if (A(ic1,indy+1).eq.0.0) then
          if ((ttc<0.5).and.(tty>=0.5)) then 
             simA = 0.0   
          else    
            A12 =  maxA
          end if
       end if   
       if (A(ic2,indy).eq.0.0) then
          if ((ttc>=0.5).and.(tty<0.5)) then 
             simA = 0.0   
          else    
            A21 =  maxA
          end if
       end if   
       simA = (1-tty)*((1-ttc)*A11+ttc*A21)+tty*((1-ttc)*A12+ttc*A(ic2,indy+1))  
    end if   
end if    
   if (simA>0.0) then
      simP = 1.0
      cash2 = cash2-F-Fy*income
   end if 
   simC = MIN(simC,0.9999*cash2)
   sav = cash2-simC
   simS = simA*sav
   simB = sav-simS
   simBpart = simB
   if (simA.EQ.0.0) then
       simBpart = 0.0
   endif

end subroutine






